import AsyncStorage from '@react-native-async-storage/async-storage';

export default class StorageUtils {
  /**
   * 获取数据
   * @param key 数据的key值
   * @return {Promise<any> | Promise}
   */

  static async getItem(key: string) {
    try {
      const value = await AsyncStorage.getItem(key);
      if (value !== null) {
        try {
          return JSON.parse(value)
        } catch (e) {
          return value;
        }
      } else {
        return null;
      }
    } catch (e) {
      console.log("get error is " + e);
      return null;
    }
  }

  /**
   * 保存数据
   * @param key
   * @param data
   */
  static setItem(key: string, data: any) {
    data = typeof data === 'object' ? JSON.stringify(data) : data;
    AsyncStorage.setItem(key, data, error => {
      if (error) {
        console.log("add error is " + error);
      }
    });
  }

  /**
   * 删除数据
   * @param key
   */
  static removeItem(key: string) {
    AsyncStorage.removeItem(key, error => {
      if (error) {
        console.log("remove error is " + error);
      }
    });
  }

  /**
   * 清除所有
   */
  static clear() {
    AsyncStorage.clear(error => {
      if (error) {
        console.log("clear error is " + error);
      }
    });
  }
}